﻿using System;
using System.Collections.Generic;

namespace Epitech.Krisk.Xna.UI.Game.InGame.Gameplay
{
    public class RiskAction
    {
        public static Random Rand { get; set; }

        public static void Move(List<KeyValuePair<Territory, Army>> from, Territory to)
        {
            Army army = new Army();

            foreach (var valuePair in from)
            {
                valuePair.Key.Owner.OwnTerritory[valuePair.Key] -= valuePair.Value;
                army += valuePair.Value;
            }

            to.Owner.OwnTerritory[to] += army;
        }

        public static bool Fight(List<KeyValuePair<Territory, Army>> atk, Territory def, out Army atkArmy, out Army defArmy)
        {
            if (Rand == null)
                throw new NullReferenceException("Rand object null");
            atkArmy = new Army();
            defArmy = def.Owner.OwnTerritory[def];
            foreach (var valuePair in atk)
            {
                valuePair.Key.Owner.OwnTerritory[valuePair.Key] -= valuePair.Value;
                atkArmy += valuePair.Value;
            }

            while (atkArmy != 0 && defArmy != 0)
            {
                int maxatk = 0;
                int cpt = 3;
                if (atkArmy.TotalSoldier() < 3)
                    cpt = atkArmy.TotalSoldier() % 3;
                for (; cpt >= 0; cpt--)
                {
                    int tmp = Rand.Next(1, 7);
                    maxatk = maxatk < tmp ? tmp : maxatk;
                }

                int maxdef = 0;
                cpt = 1;
                if (def.Owner.OwnTerritory[def].TotalSoldier() >= 2)
                    cpt = 2;
                for (; cpt >= 0; cpt--)
                {
                    int tmp = Rand.Next(1, 7);
                    maxdef = maxdef < tmp ? tmp : maxdef;
                }

                if (maxatk > maxdef)
                    defArmy--;
                else
                    atkArmy--;
            }

            if (defArmy == 0)
            {
                def.Owner.OwnTerritory.Remove(def);
                def.Owner = atk[0].Key.Owner;
                def.Owner.OwnTerritory[def] = atkArmy;
                return true;
            }
            return false;
        }
    }
}
